package com.kaizen.dispatcher;

import com.kaizen.codec.Invocation;
import com.kaizen.codec.util.JsonUtils;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 将 Invocation 分发到其对应的 MessageHandler 中
 */
@ChannelHandler.Sharable
public class MessageDispatcher extends SimpleChannelInboundHandler<Invocation> {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private MessageHandlerContainer messageHandlerContainer;

    /**
     * TODO 参数是否合理
     */
    private final ExecutorService executor =  Executors.newFixedThreadPool(200);


    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Invocation msg) {
        // <3.1> 获得 type 对应的 MessageHandler 处理器
        MessageHandler messageHandler = messageHandlerContainer.getMessageHandler(msg.getType());
        // 获得  MessageHandler 处理器的消息类
        Class<? extends Message> messageClass = MessageHandlerContainer.getMessageClass(messageHandler);
        // <3.2> 解析消息
        Message message = null;
        try {
            message = JsonUtils.transferToObj(msg.getMessage(), messageClass);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return;
        }
        // <3.3> 执行逻辑
        Message finalMessage = message;
        executor.submit(new Runnable() {

            @Override
            public void run() {
                // noinspection unchecked
                messageHandler.execute(ctx.channel(), finalMessage);
            }

        });
    }

}
